package com.example.myapplication;

import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    private static final String SERVER_IP = "192.168.29.76";
    private static final int SERVER_PORT = 8089;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 连接服务器
                    Socket socket = new Socket(SERVER_IP, SERVER_PORT);

                    // 发送数据给服务器
                    OutputStream outputStream = socket.getOutputStream();
                    String message = "Hello from Android";
                    outputStream.write(message.getBytes());

                    // 接收并显示来自服务器的响应
                    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    final String serverResponse = response.toString();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 在UI线程中更新UI
                            Toast.makeText(MainActivity.this, "Received response from server: " + serverResponse, Toast.LENGTH_SHORT).show();
                        }
                    });

                    // 关闭连接
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}